import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class SemaphoreTest {

    public static void main(String[] args) {

        // 车位总数
        Semaphore semaphore = new Semaphore(5);

        // 开车上班的人
        ThreadPoolExecutor richManThreadPool = new ThreadPoolExecutor(10, 50, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

        for (int i = 0; i < 10; i++) {
            int finalI = i;
            richManThreadPool.execute(() -> {
                try {
                    // 堵塞获取许可，即获取一个车位.
                    semaphore.acquire();
                    System.out.println("开车上班的员工：" + Thread.currentThread().getName() + " 抢到了一个车位：" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    // 假设在上班中....
                    TimeUnit.SECONDS.sleep(2);
                    // 释放许可, 开车回家了...
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}
